package Statistic;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import Main.EmailNotificator;
import Main.MovieDay;
import Main.WebsiteReader;

public class Statisticator
{

	private List<MovieDay> movieDays;

	private MovieHistoryCollection collection;

	public Statisticator()
	{
		movieDays = new ArrayList<MovieDay>();
		collection = new MovieHistoryCollection();
	}

	public void readMovieDaysFromWeb()
	{
		// load all movieday
		movieDays = new ArrayList<MovieDay>();

		// create strings for all days from today back to 2011 09 22
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");

		Calendar cal = Calendar.getInstance();
		cal.set(2011, 8, 22, 0, 0, 0); // this is when it all begun....

		Calendar endCalToday = Calendar.getInstance();

		System.out.println("Collecting all xml files from the beginning of time....");
		while (cal.before(endCalToday))
		{
			Date date = cal.getTime();

			StringBuilder dateString = new StringBuilder(dateFormatter.format(date));

			System.out.println("Reading " + dateString);
			addMovieDayFromWeb("http://reshape.ch/my-good-kino/cinema_" + dateString + ".xml");

			cal.add(Calendar.DAY_OF_YEAR, 1);
		}
	}

	public void emailNotify()
	{
		System.out.println("\nLaunching Email Notificator!");
		EmailNotificator notify = new EmailNotificator();
		notify.sendNotification(movieDays);
	}

	public void createHistoyCollection()
	{
		// create collection
		setCollection(new MovieHistoryCollection());
		getCollection().createFromMovieDays(movieDays);
	}

	public void createChartImages()
	{
		// collection.printHTML();
		getCollection().createChartImages();
	}

	private void addMovieDayFromWeb(String url)
	{
		WebsiteReader webReader = new WebsiteReader();
		String xmlString = webReader.websiteToString(url);
		if (!xmlString.isEmpty())
			movieDays.add(MovieDay.load(xmlString));
	}

	public MovieHistoryCollection getCollection()
	{
		return collection;
	}

	public void setCollection(MovieHistoryCollection collection)
	{
		this.collection = collection;
	}
}
